import React, {FC, useEffect, useState} from "react";
import {Pagination} from "antd";
import {useLocation, useNavigate, useSearchParams} from "react-router-dom";
import {LIST_PAGE_PARAM_KEY, LIST_PAGE_SIZE_PARAM_KEY} from "../constant";

type PropsType = {
    total: number
}

const ListPage: FC<PropsType> = (props: PropsType) => {
    const {total} = props;
    const [pageSize, setPageSize] = useState(10)

    const [current, setCurrent] = useState(1)

    const [searchParams] = useSearchParams()


    const nav = useNavigate()
    const {pathname} = useLocation()

    function handlePageChange(page: number, pageSize: number) {
        searchParams.set(LIST_PAGE_PARAM_KEY, page.toString())
        searchParams.set(LIST_PAGE_SIZE_PARAM_KEY, pageSize.toString())
        nav({
            pathname,
            search: searchParams.toString(),
        })
    }


    useEffect(() => {
        const page = parseInt(searchParams.get(LIST_PAGE_PARAM_KEY) || "1")
        const size = parseInt(searchParams.get(LIST_PAGE_SIZE_PARAM_KEY) || "10")
        setCurrent(page)
        setPageSize(size)
    }, [searchParams])


    return (
        <>
            <Pagination onChange={handlePageChange} current={current} defaultCurrent={1} pageSize={pageSize}
                        total={total}></Pagination>
        </>
    )
}
export default ListPage;